package com.atguigu.web;

import com.atguigu.pojo.*;
import com.atguigu.service.OrderService;
import com.atguigu.service.impl.OrderServiceImpl;
import com.atguigu.utils.JdbcUtils;
import com.atguigu.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author YAO
 * @create 2021-05-13 10:34
 */
@WebServlet(name = "OrderServlet",value = "/orderServlet")
public class OrderServlet extends BaseServlet{

    private OrderService orderService = new OrderServiceImpl();

    /**
     * 生成订单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取cart
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if (cart == null) {
            req.getRequestDispatcher("index.jsp");
            return;
        }
        //获取UserId
        User user = (User) req.getSession().getAttribute("user");
        if(user == null){
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            return;
        }

        System.out.println("OrderServlet程序在[" + Thread.currentThread().getName() + "]中");

        Integer userId = user.getId();
        //调用orderService.createOrder(Cart, UserId)
        String orderId = orderService.createOrder(cart, userId);

        req.getSession().setAttribute("orderId",orderId);

        //重定向到/pages/cart/checkout.jsp
        resp.sendRedirect(req.getContextPath() + "/pages/cart/checkout.jsp");
    }

    /**
     * 展示我的订单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void showMyOrders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取userId
        User user = (User) req.getSession().getAttribute("user");
        //如果没获取到user说明没有登录成功
        if(user == null){
            //重定向到登录页面
            resp.sendRedirect(req.getContextPath() + "/pages/user/login.jsp");
            return;
        }
        Integer userId = user.getId();
        //调用OrderService的showMyOrders()方法
        List<Order> orderList = orderService.showMyOrders(userId);
        //保存orderList到request域中
        req.setAttribute("orderList",orderList);
        //请求转发到order.jsp页面
        req.getRequestDispatcher("/pages/order/order.jsp").forward(req,resp);
    }

    protected void showOrderDetail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取订单id
        String orderId = req.getParameter("orderId");
        //获取用户
        User user = (User) req.getSession().getAttribute("user");
        //获取用户名
        String username = user.getUsername();
        //如果获取的参数为null,抛异常
        if(orderId == null || user == null){
            throw new RuntimeException();
        }
        //获取订单项
        List<OrderItem> orderItemList = orderService.showOrderDetail(orderId);
        //查询是否有此订单id
        boolean flag = false;
        for (OrderItem orderItem : orderItemList) {
            if(orderId.equals(orderItem.getOrderId())){
                flag = true;
                break;
            }
        }
        //如果用户是管理员，直接设置为true
        if("admin".equals(username)){
            flag = true;
        }
        //如果flag仍为false,说明没有匹配上的订单号,抛异常
        if(!flag){
            throw new RuntimeException();
        }
        //保存订单项到request域中
        req.setAttribute("orderItemList",orderItemList);
        //请求转发到orderItem.jsp页面
        req.getRequestDispatcher("/pages/order/orderItem.jsp").forward(req,resp);
    }

    /**
     * 展示所有订单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void showAllOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取username
        User user = (User) req.getSession().getAttribute("user");
        String username = user.getUsername();
        //如果用户不是管理员，不准访问该接口
        if(!"admin".equals(username)){
            throw new RuntimeException();
        }
        //查询所有订单
        List<Order> orderList = orderService.showAllOrders();
        //保存订单列表到request域中
        req.setAttribute("allOrderList",orderList);
        //请求转发到order_manager.jsp页面
        req.getRequestDispatcher("/pages/manager/order_manager.jsp").forward(req,resp);
    }

    /**
     * 处理分页功能
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取username
        User user = (User) req.getSession().getAttribute("user");
        String username = user.getUsername();
        //如果用户不是管理员，不准访问该接口
        if(!"admin".equals(username)){
            throw new RuntimeException();
        }
        // 1.获取请求的参数 pageNo pageSize
        int pageNo = WebUtils.parseInt(req.getParameter("pageNo"),1);
        int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), 6);
        // 2.调用bookService.page() 返回page对象
        Page<Order> page = orderService.page(pageNo, pageSize);

        page.setUrl("orderServlet?action=page");

        // 3.保存page对象到request域中
        req.setAttribute("page",page);
        // 4.请求转发到page/manager/book_manager.jsp
        req.getRequestDispatcher("/pages/manager/order_manager.jsp").forward(req,resp);

    }

    /**
     * 发货
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void sendOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名
        User user = (User) req.getSession().getAttribute("user");
        String username = user.getUsername();
        //如果不是管理员，不允许访问该接口
        if(!"admin".equals(username)){
            throw new RuntimeException();
        }
        //获取订单id
        String orderId = req.getParameter("orderId");
        //发货
        orderService.sendOrder(orderId);
        //重定向到订单列表
        resp.sendRedirect(req.getHeader("Referer"));
    }

    /**
     * 确认收货
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void receiveOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取订单id
        String orderId = req.getParameter("orderId");
        //收货
        orderService.receiveOrder(orderId);
        //重定向到原来的页面
        resp.sendRedirect(req.getHeader("Referer"));
    }

    /**
     * 删除订单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取订单id
        String orderId = req.getParameter("id");
        //删除该订单对应的小项
        orderService.deleteOrderItemsByOrderId(orderId);
        //删除该订单
        orderService.deleteOrderByOrderId(orderId);
        //跳转回原来的页面
        resp.sendRedirect(req.getHeader("Referer"));
    }
}
